package com.wo.cloud.auth.sms;

import cn.hutool.core.util.ObjectUtil;
import com.wo.cloud.auth.service.UserService;
import com.wo.cloud.auth.service.impl.UserDetailServiceImpl;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * @author liry
 * @version 1.0
 * @date Created on 2021/5/25 14:14
 * Description: 短信验证码验证提供者 （loadUserByMobile()）
 */

@AllArgsConstructor
public class SmsCodeAuthenticationProvider implements AuthenticationProvider {


    private final UserService userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        SmsCodeAuthenticationToken authenticationToken = (SmsCodeAuthenticationToken) authentication;

        // 根据登录Mobile 获取用户信息
        Object principal = authenticationToken.getPrincipal();
        UserDetails userDetails = userDetailsService.loadUserByMobile((String) principal);

        if (ObjectUtil.isNull(userDetails)) {
            throw new InternalAuthenticationServiceException("手机号不存在");
        }

        SmsCodeAuthenticationToken authenticationResult = new SmsCodeAuthenticationToken(userDetails, userDetails.getAuthorities());

        // 将 认证详情进行封装
        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SmsCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
